//
//  SetNickNameVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/14.
//

import UIKit


enum NickNameType {
    case my
    case user
    case group
    case groupName
}

class SetNickNameVC: BaseVC {
    

    
    var type: NickNameType!
    var SId: String!
    @IBOutlet weak var nickTextField: UITextField!
    
    // 初始化时接收闭包
    var dismissCompletion: (() -> Void)?

//        init(dismissCompletion: (() -> Void)?) {
//            self.dismissCompletion = dismissCompletion
//            super.init(nibName: nil, bundle: nil)
//        }
    
    init(type: NickNameType!, SId: String!,dismissCompletion: (() -> Void)?) {
        super.init(nibName: nil, bundle: nil)
        self.dismissCompletion = dismissCompletion
        self.type = type
        self.SId = SId
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        nameLab.text = KLocalizedString("SettingName")
//        saveBtn?.setTitle(KLocalizedString("SettingSave"), for: .normal)
        nickTextField.placeholder = KLocalizedString("SettingInput")
        
        self.view.backgroundColor = UIColor.init(hex: 0xF2F2F7)
        
//        let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick))
//        view.addGestureRecognizer(tap)

        if type == .my || type == .user {
            let user = gosnUser.getUserInfo(SId)
            nickTextField.text = user?.getAlias()
        } else if type == .group {
            let user = gosnUser.getUserInfoDefault(gosnUser.myId())
            let member = gosnMember.getMemberInfoDefault(SId, user.userId)
            if member.alias.count > 0 {
                nickTextField.text = member.alias
            }else{
                nickTextField.text = user.getAlias()
            }
            
        }
        nickTextField.becomeFirstResponder()
    }

    @IBAction func back(_ sender: Any) {
        self.dismiss(animated: true)
    }
    
    @IBAction func done(_ sender: Any) {
        self.saveBtnClick()
    }


    func saveBtnClick() {
        guard nickTextField.text?.count ?? 0 <= 12 else {
            MHAlert.showMessage("不能超过12个字")
            return
        }
        
        if let dic = UserDefaults.standard.dictionary(forKey: MHHYCrossImSensitiveWords),
           let sensitiveWordsArr = dic["keywordArray"] as? [String] {
            if sensitiveWordsArr.contains(where: nickTextField.text!.contains) {
                switch type {
                case .my:
                    MHAlert.showMessage("昵称违规，请重新输入")
                case .user:
                    MHAlert.showMessage("昵称违规，请重新输入")
                case .group:
                    MHAlert.showMessage("群组昵称违规，请重新输入")
                default:
                    MHAlert.showMessage("群昵称违规，请重新输入")
                }
                return
            }
        }
        
        MHAlert.showLoading()
        switch type {
        case .user:
//            await gosnFriend.setAlias(<#T##osnId: String##String#>, <#T##alias: String##String#>)
            
            Task{
                let res = await gosnFriend.setAlias(SId, nickTextField.text!)
                await MainActor.run {
                    if res{
                        self.dismissCompletion?()
                        DispatchQueue.main.async {
                            MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
                            self.dismiss(animated: true)
                        }
                    }else{
                        MHAlert.showMessage(KLocalizedString("请求超时"))
                    }
                }
            }
            

        case .group:
            
            Task{
                await gosnMember.setMemberAlias(SId, nickTextField.text!)
                await MainActor.run {
                    self.dismissCompletion?()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
                        MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
                        self.dismiss(animated: true)
                    }))
                }
            }
            
//            DMCCIMService.getInstance().setGroupMemberAlias(SId, alias: nickTextField.text!) {
//                self.dismissCompletion?()
//                DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
//                    MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
//                    self.dismiss(animated: true)
//                }))
//            } error: { error in
//                
//            }
            
        case .my:
            
            
            Task{
                let res = await gosnUser.setAlias(nickTextField.text!)
                await MainActor.run {
                    if res{
                        self.dismissCompletion?()
                        DispatchQueue.main.async {
                            MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
                            self.dismiss(animated: true)
                        }
                    }else{
                        MHAlert.showMessage(KLocalizedString("请求超时"))
                    }
                }
            }

            
        case .groupName:
            
            
            Task{
                let res = await gosnGroup.setGroupName(SId, nickTextField.text!)
                await MainActor.run {
                    if res{
                        self.dismissCompletion?()
                        DispatchQueue.main.async {
                            MHAlert.showMessage(KLocalizedString("GroupNameViolatingRegulations"))
                            self.dismiss(animated: true)
                        }
                    }else{
                        MHAlert.showMessage(KLocalizedString("请求超时"))
                    }
                }
            }
            
        case .none: break
            
        }
        
    }

        // MARK: - UITextField Delegate Methods
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if string == "\n" {
                textField.resignFirstResponder()
                return false
            } else if string.isEmpty {
                return true
            }
            return true
        }
    

    

}
